package com.learn.base.test;

import org.junit.Test;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class HashMapTest {


    @Test
    public void HashMapDemo() throws Exception {
        Map<Integer, Integer> hashMap = new HashMap<Integer, Integer>(13);

        for (Integer i = 1; i <= 40; i++) {
            hashMap.put(i, i);
            System.out.println("map size = " + hashMap.size() + ", map capacity = " + tableLength((HashMap<?, ?>) hashMap));
        }

    }


    public int tableLength(HashMap<?, ?> map) throws Exception {
        Field table = HashMap.class.getDeclaredField("table");
        table.setAccessible(true);
        Object[] obj = (Object[]) table.get(map);
        return obj.length;
    }

    static final int MAXIMUM_CAPACITY = 1 << 30;

    static final int tableSizeFor(int cap) {
        int n = cap - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }

    @Test
    public void calcCapacity() {
        int i = tableSizeFor(13);

        System.out.println("i=:" + i);

        int n = 20 -1;
        // 10011  按右位移1位
        n |= n >>> 1;
        System.out.println("无符号右移运算:" + n);
        System.out.println(-15 >>> 3);
    }

    @Test
    public void calcNumber() {
        int number1 = 5 & 6;
        System.out.println("number1:" + number1);
        int number2 = 5 | 6;
        System.out.println("number2:" + number2);

        System.out.println("将2左移两位：" + (2 << 2));
        System.out.println("将8右移两位：" + (8 >> 2));
    }
}
